<template>
  <div v-loading="loading" class="product-main">
    <!-- <div class="left-main fl">
      <div class="btn-group flex-x-center-center">
        <el-button type="primary" size="medium" round @click="add">新增商品</el-button>
      </div>
      <div class="category-tree-container">
        <el-scrollbar style="height:100%" class="hid-scrollbar-x">
          <el-tree
            ref="categoryTree"
            :data="categoryTreeOptions"
            :props="categoryTreeProps"
            :expand-on-click-node="false"
            :highlight-current="true"
            node-key="id"
            default-expand-all
            @node-click="handleTree"
          >
            <span slot-scope="{ node, data }">
              <span style="width: 100%;padding-right: 10px;">{{ node.label }}</span>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
    </div> -->
    <div class="right-main">
      <div class="scrollbar-container">
        <el-scrollbar style="height: 100%" class="hid-scrollbar-x">
          <!-- filter start -->
          <div class="filter-container">
            <el-form
              ref="filterForm"
              :model="filterForm"
              inline
              label-width="100px"
              size="small"
            >
              <div>
                <el-form-item prop="title" label="商品名称：">
                  <el-input v-model="filterForm.title" />
                </el-form-item>
                <el-form-item prop="categoryId" label="分类">
                  <!-- <el-select
                    v-model="filterForm.categoryId"
                    placeholder="请选择分类"
                  >
                    <el-option label="全部" value="all" />
                    <el-option
                      v-for="(item, key) in goodsTypeOptions"
                      :key="key"
                      :label="item"
                      :value="key"
                    />
                  </el-select> -->
                  <el-cascader
                    v-model="filterForm.categoryId"
                    :options="categoryTreeOptions"
                    :show-all-levels="false"
                    :props="{
                      expandTrigger: 'hover',
                      checkStrictly: true,
                      label: 'title',
                      value: 'id',
                    }"
                    class="w-300"
                  />
                </el-form-item>
                <el-form-item prop="status" label="状态：">
                  <el-select
                    v-model="filterForm.status"
                    placeholder="请选择状态"
                  >
                    <el-option label="全部" value="all" />
                    <el-option label="上架" value="1" />
                    <el-option label="下架" value="0" />
                  </el-select>
                </el-form-item>
                <el-form-item prop="goodsType" label="商品类型：">
                  <el-select
                    v-model="filterForm.goodsType"
                    placeholder="请选择"
                  >
                    <el-option label="全部" value="all" />
                    <el-option
                      v-for="(item, key) in goodsTypeOptions"
                      :key="key"
                      :label="item"
                      :value="key"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item prop="storeId" label="门店：" v-if="mainShopStatus">
                  <el-select
                    v-model="filterForm.storeId"
                    placeholder="请选择门店"
                  >
                    <el-option label="全部" value="all" />
                    <el-option
                      v-for="(item, key) in storeList"
                      :label="item.name"
                      :value="item.storeId"
                      :key="key"
                    />
                  </el-select>
                </el-form-item>
                <!-- <el-form-item prop="title" label="商品名称：">
                  <el-input v-model="filterForm.title" />
                </el-form-item>
                <el-form-item prop="goodsNo" label="商品编码：">
                  <el-input v-model="filterForm.goodsNo" />
                </el-form-item>
                <el-form-item prop="barCode" label="国际条码：">
                  <el-input v-model="filterForm.barCode" />
                </el-form-item> -->

                <!--<el-form-item prop="categoryId" label="商品类目：">-->
                <!--  <el-cascader v-model="filterForm.categoryId" :options="categoryTreeOptions" :show-all-levels="false" :props="{ expandTrigger: 'hover',checkStrictly: true,label:'title' ,value:'id'}" class="w-300"/>-->
                <!--</el-form-item>-->
                <!-- <el-form-item prop="title" label="商品状态：">
                    <el-select v-model="filterForm.status" placeholder="请选择">
                      <el-option label="全部" value="all"></el-option>
                      <el-option
                        v-for="(item,key) in statusOptions"
                        :key="key"
                        :label="item"
                        :value="key"
                      ></el-option>
                    </el-select>
                  </el-form-item>-->

                <!-- </div> -->
                <!-- <div> -->
                <el-form-item label=" ">
                  <el-button type="primary" @click="search">查 询</el-button>
                  <el-button @click="reset">重 置</el-button>
                  <el-button
                    type="primary"
                    :disabled="chooseList.length < 1"
                    @click="batchAction"
                    >批量操作</el-button
                  >
                  <el-button type="primary" v-if="mainShopStatus" @click="add"
                    >新增商品</el-button
                  >
                </el-form-item>
              </div>
            </el-form>
          </div>
          <!-- filter end -->

          <!-- table start -->
          <div class="table-container">
            <el-table
              :data="list"
              border
              stripe
              style="width: 100%"
              size="small"
              element-loading-text="加载中"
              empty-text="暂无数据"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="title" label="商品名称" />
              <!-- <el-table-column prop="goodsNo" label="商品编码" /> -->
              <!-- <el-table-column prop="barCode" label="国际条码" /> -->
              <el-table-column prop="description" label="价格/元">
                <template slot-scope="scope">
                  <div>最低价格：{{ scope.row.minPrice / 100 }}</div>
                  <div>最高价格：{{ scope.row.maxPrice / 100 }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="barCode" label="关联门店" align="center" v-if="mainShopStatus">
                <template slot-scope="scope">
                  <el-popover
                    placement="right"
                    width="400"
                    trigger="click"
                    v-if="scope.row.shopNames&& scope.row.shopNames.length> 0"
                  >
                    <div style="max-height: 200px; overflow-y: scroll">
                      <div v-for="item in scope.row.shopNames" :key="item">
                        {{ item }}
                      </div>
                    </div>
                    <div slot="reference">
                      <div
                        style="color: #ffb847"
                        v-for="(item, index) in scope.row.shopNames.slice(0, 2)"
                        :key="index"
                      >
                        {{ item }}
                      </div>
                      <div
                        class="el-icon-more"
                        style="color: #ffb847"
                        v-if="scope.row.shopNames.length > 1"
                      />
                    </div>
                  </el-popover>
                  <div v-else>无</div>
                </template>
              </el-table-column>
              <el-table-column prop="defaulted" label="商品类型">
                <template slot-scope="scope">{{
                  goodsTypeOptions[scope.row.goodsType]
                }}</template>
              </el-table-column>
              <el-table-column prop="categoryName" label="商品类目">
                <template slot-scope="scope">
                  <span v-if="scope.row.categoryName">
                    <span
                      v-for="(item, index) in scope.row.categoryName"
                      :key="index"
                    >
                      {{ item }}
                      <span v-if="index + 1 !== scope.row.categoryName.length"
                        >/</span
                      >
                    </span>
                  </span>
                  <span v-else>无</span>
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="品牌">
                <template slot-scope="scope">
                  <span v-if="scope.row.brand">{{ scope.row.brand }}</span>
                  <span v-else>无</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="barCode"
                label="总销量/本门店销量"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.taotalSells }} / {{ scope.row.currentSells }}
                </template>
              </el-table-column>
              <el-table-column prop="barCode" align="center">
                <template slot="header" slot-scope="scope">
                  商品状态
                  <el-tooltip placement="right">
                    <div slot="content">
                      上架指门店可售卖，<br />门店自行可设置上下架<br />下架指门店不可售卖
                    </div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  {{ scope.row.status == 0 ? "下架" : "上架" }}
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="edit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="del(scope.row)"
                    v-if="mainShopStatus"
                    >删除</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="upStatus(scope.row)"
                    >{{ scope.row.status != 0 ? "下架" : "上架" }}</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="exportPrice(scope.row)"
                    v-if="mainShopStatus"
                    >出价/库存</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination-direction
              v-if="paginationConfig.total !== 0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />
          </div>
          <!-- table end -->
        </el-scrollbar>
      </div>
    </div>
    <DialogExportPrice ref="DialogExportPrice" />
    <DialogBatchStatus ref="DialogBatchStatus" />
  </div>
</template>

<script>
import {
  productList,
  delProduct,
  batchStatus,
  getGoodsStoreList,
} from "@/views/wxaMallModule/api/productPublic";
import { storeList } from "@/views/wxaMallModule/api/shop";
import { categoryTree } from "@/views/wxaMallModule/api/category";
import { mapState } from "vuex";
import DialogExportPrice from "./DialogExportPrice";
import DialogBatchStatus from "./DialogBatchStatus";
export default {
  props: {
    modeInfo: {
      type: Object,
    },
  },
  data() {
    return {
      // 配置
      goodsTypeOptions: {
        100: "实物商品",
        101: "配件商品",
        200: "卡/券包",
        // 300: "同城配送",
      },
      statusOptions: {
        0: "已下架",
        1: "已上架",
      },
      categoryTreeOptions: [],
      // 分页配置
      paginationConfig: {
        direction: "center", // 分页位置
        layout: "total, sizes, prev, pager, next, jumper", // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10, // 每页条数-默认10
      },
      categoryTreeProps: {
        label: "title",
      },
      // 状态
      loading: false,
      // 数据
      filterForm: {
        goodsType: "all",
        // barCode: "",
        // brandId: "",
        categoryId: "all",
        // goodsNo: "",
        status: "all",
        title: "",
        status: "all",
        storeId: "",
      },
      list: [],
      chooseList: [],
      storeList: [],
    };
  },
  components: {
    DialogExportPrice,
    DialogBatchStatus,
  },
  computed: {
    refresh() {
      return this.modeInfo;
    },
    ...mapState({
      mainShopStatus: (state) => state.user.mainShopStatus,
    }),
  },
  watch: {
    refresh(val) {
      if (val.data === "refresh") {
        this.fetchData();
      }
    },
  },
  created() {},
  mounted() {
    this.fetchData();
    this.getCategoryOptions();
    this.getShopList();
    console.log(this.$store.state.user)
  },
  methods: {
    /**
     * 数据组
     */
    // 获取列表
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum;
      this.filterForm.pageSize = pageSize;
      this.filterForm.mainShopStatus = this.mainShopStatus;
      if(this.filterForm?.categoryId != 'all'&&this.filterForm?.categoryId.length>0){
          this.filterForm.categoryId = this.filterForm?.categoryId[this.filterForm?.categoryId.length-1]
      }
      const params = Object.assign({}, this.filterForm);
      for (const key in params) {
        if (params[key] === "" || params[key] === "all") {
          delete params[key];
        }
      }
      this.loading = true;
      productList(params)
        .then((res) => {
          this.list = res.data.list;
          this.paginationConfig.total = res.data.total;
          this.paginationConfig.page = res.data.pageNum;
          // this.$refs.categoryTree.setCurrentKey(this.filterForm.categoryId);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData();
    },

    // 分页page改变
    pageChange() {
      this.fetchData();
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree().then((res) => {
          // this.categoryTreeOptions = [
          //   {
          //     categoryNo: '',
          //     children: undefined,
          //     id: 0,
          //     parentId: 0,
          //     ranking: 0,
          //     title: '全部'
          //   }
          // ].concat(this.formatTreeData(res.data))
          this.categoryTreeOptions =this.formatTreeData(res.data),
          this.$nextTick(() => {
            // this.$refs.categoryTree.setCurrentKey(this.filterForm.categoryId);
          });
        });
      });
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.formatTreeData(data[i].children);
        }
      }
      return data;
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.fetchData(1);
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields();
      this.fetchData(1);
    },

    // 新增
    add() {
      this.$emit("update:modeInfo", {
        mode: "productForm",
        modePage: "ProductManage",
        data: "",
      });
    },

    // 编辑
    edit(row) {
      this.$emit("update:modeInfo", {
        mode: "productForm",
        modePage: "ProductManage",
        data: row.id,
      });
    },

    // 删除
    del(row) {
      this.$confirm(`确定删除商品：【${row.title}】?`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
        roundButton: true,
      })
        .then(() => {
          this.loading = true;
          delProduct({ goodsId: row.id })
            .then((res) => {
              this.fetchData();
            })
            .catch((err) => {})
            .finally(() => {});
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(val) {
      this.chooseList = val;
    },
    batchAction() {
      this.$refs.DialogBatchStatus.open(this.chooseList).then((res) => {
        this.chooseList = [];
        this.fetchData();
      });
    },
    upStatus(row) {
      this.$confirm(
        `注：部分规格${row.status != 0 ? "下架" : "上架"}可在商品详情操作`,
        `是否确定${row.status != 0 ? "下架" : "上架"}该商品全部规格？`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          center: true,
        }
      ).then(() => {
        let { mainShopStatus } = this;
        batchStatus({
          goodsIds: [row.id],
          status: row.status == 0 ? 1 : 0,
          mainShopStatus,
        }).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "更新状态成功",
          });
        });
      });
    },
    getShopList(mode = null) {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.storeList = res.data;
          })
          .catch(() => {})
          .finally(() => {
            resolve();
          });
      });
    },
    exportPrice(row) {
      this.$refs.DialogExportPrice.open({ goodsId: row.id });
    },
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.left-main {
  padding: 10px;
  border-radius: 5px;
  margin-right: 10px;
  background-color: #fff;
  min-width: 180px;
  font-size: 14px;
  .category-tree-container {
    height: calc(100vh - 260px);
  }
  .btn-group {
    height: 50px;
  }
  ::v-deep
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: $primary !important;
    color: #fff;
  }
}
.right-main {
  overflow: hidden;
  padding: 20px 10px;
  border-radius: 5px;
  background-color: #fff;
  .scrollbar-container {
    height: calc(100vh - 230px);
  }
  /* 查询 */
  .filter-container {
    .el-input,
    .w-300,
    .el-select {
      width: 300px;
    }
  }
}
</style>
